/*
 * @Author: chengjiang
 * @Date: 2025-07-25 23:29:15
 * @Description:
 */
package server

import (
	"fmt"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"time"

	"com.damai.services/common/auth"
)

type ProxyHandler struct {
	consul *ConsulService
	// breaker   *breaker.BreakerMiddleware
	// jwtSecret string
}

func NewProxyHandler(
	consul *ConsulService,
	// breaker *breaker.BreakerMiddleware,
	// jwtSecret string,
) *ProxyHandler {
	return &ProxyHandler{
		consul: consul,
		// breaker:   breaker,
		// jwtSecret: jwtSecret,
	}
}

// 代理逻辑：转发请求到目标服务
func (h *ProxyHandler) Proxy(serviceName string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 从Consul获取服务实例
		targetURL, err := h.consul.GetInstance(serviceName)
		if err != nil {
			http.Error(w, fmt.Sprintf("服务无可用实例: %v", err), http.StatusServiceUnavailable)
			return
		}
		url, _ := url.Parse(targetURL)
		proxy := httputil.NewSingleHostReverseProxy(url)
		proxy.Transport = &http.Transport{
			Proxy: http.ProxyFromEnvironment,
			DialContext: (&net.Dialer{
				Timeout:   200 * time.Millisecond,
				KeepAlive: 30 * time.Second,
			}).DialContext,
			MaxIdleConns:          1000,
			MaxIdleConnsPerHost:   100,
			MaxConnsPerHost:       100,
			DisableCompression:    true,
			IdleConnTimeout:       90 * time.Second,
			TLSHandshakeTimeout:   10 * time.Second,
			ExpectContinueTimeout: 1 * time.Second,
		}

		// 捕获上游响应
		_ = auth.DefaultResponseEncoder(w, r, 1)
		proxy.ServeHTTP(w, r)
	}
}
